<template>
	<van-button @click="onFollow" :loading="loading" v-if="isFollowed" round size="small">已关注
	</van-button>
	<van-button @click="onFollow" :loading="loading" v-else type="info" color="#3296fa" round size="small" icon="plus">
		关注
	</van-button>
</template>

<script>
	import {
		addFollow,
		deleteFollow
	} from '@/api/user.js'

	export default {
		model: {
			prop: 'isFollowed',
			event: 'updateIsFollowed'
		},

		props: {
			isFollowed: {
				type: Boolean,
				required: true
			},

			userId: {
				type: [Number, String, Object],
				required: true
			}
		},

		data() {
			return {
				loading: false
			}
		},

		methods: {
			async onFollow() {
				this.loading = true
				try {
					if (this.isFollowed) {
						const {
							data: res
						} = await deleteFollow(this.userId)
					} else {
						const {
							data: res
						} = await addFollow(this.userId)
					}

					this.$emit('updateIsFollowed', !this.isFollowed)
				} catch (e) {
					let message = '操作失败，请稍后重试' + e
					if (e.response && e.response.status === 400) {
						message = '不能关注自己'
					}
					this.$toast(message)
				}
				this.loading = false
			}
		},
	}
</script>

<style scoped>

</style>
